<?php
/**
 * Created by PhpStorm.
 * User: tangchao
 * Date: 19-3-19
 * Time: 下午2:13
 */

namespace App\Model;


use EasySwoole\Core\Component\Di;

class Base
{
    public $db = "";
    public $tableName;

    public function __construct()
    {
        if (empty($this->tableName)){
            throw new \Exception("No specified table name");
        }

        $db = Di::getInstance()->get("MYSQL");
        if ($db instanceof \MysqliDb){
            $this->db = $db;
        }else{
            throw new \Exception("Db error");
        }
    }

    public function add($data)
    {
        if (empty($data) || !is_array($data)){
            return false;
        }
        return $this->db->insert($this->tableName,$data);
    }

    public function getById($id)
    {
        $id = intval($id);
        if (empty($id)){
            return [];
        }

        $this->db->where("id", $id);
        $result = $this->db->getOne($this->tableName);
        return $result ?? [];
    }

    /**
     * 分页列表
     * @param $page
     * @param int $size
     * @param array $condition
     * @return array
     * @throws \Exception
     */
    public function getList($page, $condition=[], $size=0, $orderBy = [])
    {
        if (!empty($size)){
            $this->db->pageLimit = $size;
        }
        if (!empty($condition)){
            $this->db->where($condition);
        }
        if (empty($orderBy)){
            $this->db->orderBy('id','DESC');
        }else{
            $this->db->orderBy('id','DESC',$orderBy);
        }

        $lists = $this->db->paginate($this->tableName,$page);
        $data = [
            'total_page' => $this->db->totalPages,
            'page_size' => $this->db->pageLimit,
            'count' => intval($this->db->totalCount),
            'lists' => $lists,
        ];
        return $data;
    }

    public function videoTimeFormat($time)
    {
        if (!empty($time)){
            return gmstrftime("%H:%M:%S",$time);
        }else{
            return '';
        }

    }

    public function timeFormat($time)
    {
        if (!empty($time)){
            return date('Ymd H:i:s',$time);
        }else{
            return '';
        }
    }
}